package com.meta;


import com.google.auto.service.AutoService;
import com.meta.context.MetaAnnotationProcessorContext;
import com.meta.builder.freemarker.FreemarkerProcessor;
import com.meta.internal.Options;

import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import java.util.HashMap;
import java.util.Set;

@AutoService(Processor.class)
@SupportedAnnotationTypes({"com.meta.annotation.MetaGenAnnotation"})
@SupportedSourceVersion(SourceVersion.RELEASE_17)
@SupportedOptions({"meta.typeTip", "meta.propertiesTip"})
public class MetaProcessor extends AbstractProcessor {
    private MetaAnnotationProcessorContext annotationProcessorContext;
    private Options options;
    private static HashMap<String, Integer> maps = new HashMap<>();
    private FreemarkerProcessor freemarkerProcessor;

    public synchronized void init(ProcessingEnvironment processingEnv) {

        super.init(processingEnv);
        this.options = this.createOptions(processingEnv);
        this.freemarkerProcessor = new FreemarkerProcessor(options);
        this.annotationProcessorContext = new MetaAnnotationProcessorContext(processingEnv.getElementUtils(), processingEnv.getTypeUtils(), processingEnv.getMessager(), freemarkerProcessor, options);
    }

    /**
     * 配置属性生成
     *
     * @param processingEnv
     * @return
     */
    private Options createOptions(ProcessingEnvironment processingEnv) {
        Options options = new Options();
        String type = this.processingEnv.getOptions().getOrDefault("meta.typeTip", "type");
        options.setTypeTip(type);
        String propertiesTip = this.processingEnv.getOptions().getOrDefault("meta.propertiesTip", "properties");
        options.setPropertiesTip(propertiesTip);
        options.setSourceType(this.processingEnv.getOptions().getOrDefault("meta.sourceType", "http"));
        options.setProcessingEnv(processingEnv);
        return options;
    }

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        for (TypeElement annotation : annotations) {
            Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(annotation);
            for (Element element : annotatedElements) {
                annotationProcessorContext.process(element);
            }
        }
        return false;
    }
}
